import json

import requests
from DataFactory.common import mysql_conn
from DarlingTestTools.settings import logger


def create_quotation(host, customer_type, payment_method, quotation_type, quotation_status, token_needed):
    logger.info("Start to create quotation: \n" + host + "\n" + customer_type + "\n" + payment_method + "\n" + quotation_type + "\n" + str(quotation_status) + "\n" + token_needed)
    global quotation_number, cur, conn, quotation_result, eggPaymentMethodCode, quotation_id
    orders = []
    session = requests.session()
    headers = {
        "token": token_needed,
        "countryId": "1001",
        "Content-Type": "application/json"
    }

    logger.info("Headers is : " + str(headers))

    if payment_method == "CreditPayment":
        eggPaymentMethodCode = 1
    elif payment_method == "eggPaymentMethodCode":
        eggPaymentMethodCode = 7
    elif payment_method == "BankTransferBeforeDelivery":
        eggPaymentMethodCode = 6

    logger.info("eggPaymentMethodCode is : " + str(eggPaymentMethodCode))

    logger.info("quotation type is : " + str(quotation_type))

    quotation_data_normal_search = {
        "salesAmount": 21938.01,
        "createSource": "",
        "customerId": 17965,
        "lineId": "",
        "internalRemark": "",
        "customerRemark": "",
        "expectedDelivery": 3,
        "eggPaymentMethodCode": eggPaymentMethodCode,
        "allPutInStorage": 0,
        "quotationShipIdInfoVO":
            {"stateId": 32535,
             "province": "Trat",
             "cityId": 32538,
             "city": "Khlong Yai",
             "districtId": 32538,
             "district": "Khlong Yai",
             "address": "测试啦啦啦啦",
             "shipId": "SH17965_1",
             "contact": "Test ID",
             "mobile": "151515151"
             },
        "quotationVehicleTypeList":
            [
                {
                    "vehicleBrandId": 2,
                    "vehicleSerialId": 1397,
                    "yearCapacityId": "",
                    "vehicleModelId": ""
                }
            ],
        "priceIdentityId": 1,
        "pictures": [],
        "quotationAttachmentBOList": [],
        "itemGroupList":
            [
                {
                    "customerProductName": "8980985860",
                    "customerLine": 1,
                    "qty": 3,
                    "selectStatus": 1,
                    "quotationItemList": [
                        {
                            "skuOrgId": 607235,
                            "skuId": 571685,
                            "orgId": 6,
                            "materialId": 2061066,
                            "eggSku": "8980985860",
                            "brand": "ISUZU",
                            "oeNumber": "8980985860",
                            "brandSku": None,
                            "productName": "ชุดไฟท้าย TFR/TFS'2007",
                            "productNameLocal": "ชุดไฟท้าย TFR/TFS'2007",
                            "productNameBi": None,
                            "materialType": 1,
                            "shopId": 2,
                            "shopName": "EGG Search",
                            "salesPriceWithoutVat": 652,
                            "salesPrice": 697.64,
                            "salesAmountWithoutVat": None,
                            "cataloguePrice": 815,
                            "discount": 20,
                            "distanceInt": 8015,
                            "distance": "8KM",
                            "latestReplacementOeList": [],
                            "eggShopPutOnSku": False,
                            "checked": True,
                            "productNameTh": "ชุดไฟท้าย TFR/TFS'2007",
                            "selectStatus": 1
                        }
                    ]
                },
                {
                    "customerProductName": "8974050051",
                    "customerLine": 2,
                    "qty": 12,
                    "selectStatus": 1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId": 582297,
                                "skuId": 546747,
                                "orgId": 6,
                                "materialId": 2036128,
                                "eggSku": "8974050051",
                                "brand": "ISUZU",
                                "oeNumber": "8974050051",
                                "brandSku": None,
                                "productName": "สติกเกอร์ TFR/TFS'2007",
                                "productNameLocal": "สติกเกอร์ TFR/TFS'2007",
                                "productNameBi": None,
                                "materialType": 1,
                                "shopId": 2,
                                "shopName": "EGG Search",
                                "salesPriceWithoutVat": 36,
                                "salesPrice": 38.52,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice": 45,
                                "discount": 20,
                                "distanceInt": 8015,
                                "distance": "8KM",
                                "latestReplacementOeList": [],
                                "eggShopPutOnSku": False,
                                "checked": True,
                                "productNameTh": "สติกเกอร์ TFR/TFS'2007",
                                "selectStatus": 1
                            }
                        ]
                },
                {
                    "customerProductName": "B45A34015C",
                    "customerLine": 3,
                    "qty": 6,
                    "selectStatus": 1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId": 335289,
                                "skuId": 299739,
                                "orgId": 6,
                                "materialId": 1789120,
                                "eggSku": "B45A34015C",
                                "brand": "Mazda",
                                "oeNumber": "B45A34015C",
                                "brandSku": None,
                                "productName": "COVER,DUST",
                                "productNameLocal": "ยางครอบกันฝุ่น",
                                "productNameBi": None,
                                "materialType": 1,
                                "shopId": 2,
                                "shopName": "EGG Search",
                                "salesPriceWithoutVat": 463.5,
                                "salesPrice": 495.95,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice": 515,
                                "discount": 10,
                                "distanceInt": 8015,
                                "distance": "8KM",
                                "latestReplacementOeList": [],
                                "eggShopPutOnSku": False,
                                "checked": True,
                                "productNameTh": "ยางครอบกันฝุ่น",
                                "selectStatus": 1
                            }
                        ]
                },
                {
                    "customerProductName": "D72101HZ1A",
                    "customerLine": 4,
                    "qty": 3,
                    "selectStatus": 1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId": 313060,
                                "skuId": 289558,
                                "orgId": 6,
                                "materialId": 1766891,
                                "eggSku": "D72101HZ1A",
                                "brand": "Nissan",
                                "oeNumber": "D72101HZ1A",
                                "brandSku": "",
                                "productName": "BOOSTER ASSY-BRAKE",
                                "productNameLocal": "หม้อลมเบรค มี IDLE STOP K13T,ABS,E12T",
                                "productNameBi": None,
                                "materialType": 1,
                                "shopId": 2,
                                "shopName": "EGG Search",
                                "salesPriceWithoutVat": 4203,
                                "salesPrice": 4497.21,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice": 5000,
                                "discount": 16,
                                "distanceInt": 8015,
                                "distance": "8KM",
                                "latestReplacementOeList": [],
                                "eggShopPutOnSku": False,
                                "checked": True,
                                "productNameTh": "หม้อลมเบรค มี IDLE STOP K13T,ABS,E12T",
                                "selectStatus": 1
                            }
                        ]
                },
                {
                    "customerProductName": "S3055925",
                    "customerLine": 5,
                    "qty": 5,
                    "selectStatus": 1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId": 1602097,
                                "skuId": 1284319,
                                "orgId": 6,
                                "materialId": 3055925,
                                "eggSku": "S3055925",
                                "brand": "Nissan",
                                "oeNumber": "540103BG1A",
                                "brandSku": None,
                                "productName": "SPRING FRONT",
                                "productNameLocal": "สปริงโช๊คอัพหน้า",
                                "productNameBi": None,
                                "materialType": 1,
                                "shopId": 2,
                                "shopName": "EGG Search",
                                "salesPriceWithoutVat": 424,
                                "salesPrice": 453.68,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice": 530,
                                "discount": 20,
                                "distanceInt": 8015,
                                "distance": "8KM",
                                "latestReplacementOeList": [],
                                "eggShopPutOnSku": False,
                                "checked": True,
                                "productNameTh": "สปริงโช๊คอัพหน้า",
                                "selectStatus": 1
                            }
                        ]
                },
                {
                    "customerProductName": "91604S5A003",
                    "customerLine": 6,
                    "qty": 8,
                    "selectStatus": 1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId": 55699,
                                "skuId": 54326,
                                "orgId": 6,
                                "materialId": 1522362,
                                "eggSku": "91604S5A003",
                                "brand": "Honda",
                                "oeNumber": "91604S5A003",
                                "brandSku": None,
                                "productName": "GROMMET, HOOD STAY",
                                "productNameLocal": "หมุดยึดขาคล้ำกระโปรงหน้า",
                                "productNameBi": None,
                                "materialType": 1,
                                "shopId": 2,
                                "shopName": "EGG Search",
                                "salesPriceWithoutVat": 75.6,
                                "salesPrice": 80.89,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice": 84,
                                "discount": 10,
                                "distanceInt": 8015,
                                "distance": "8KM",
                                "latestReplacementOeList": [],
                                "eggShopPutOnSku": False,
                                "checked": True,
                                "productNameTh": "หมุดยึดขาคล้ำกระโปรงหน้า",
                                "selectStatus": 1
                            }
                        ]
                }
            ],
        "customerInquiryTimeLong": 1586416711301,
        "firstReactionTimeLong": 1586416711301,
        "answerToCustomerTimeLong": 1586416711301,
        "customerConfirmQuotationTimeLong": 1586416711301,
        "carPlateNo": "",
        "vinCode": "",
        "customerReferenceOrderNo": ""}

    quotation_data_insurance_search = {
        "salesAmount": 233934.05, "createSource": "", "customerId": 505145, "lineId": "", "internalRemark": "", "customerRemark": "", "expectedDelivery": 3, "eggPaymentMethodCode": 1, "allPutInStorage": 1, "quotationShipIdInfoVO": {"stateId": 1001, "province": "Bangkok", "cityId": 33370, "city": "Phatthanakan", "districtId": 33371, "district": "Suan Luang", "address": "117|13", "shipId": "SH505145_1", "contact": "คุณวิโรจน์", "mobile": "899223633"},
        "quotationVehicleTypeList": [{"vehicleBrandId": 2, "vehicleSerialId": 1397, "yearCapacityId": "", "vehicleModelId": ""}], "priceIdentityId": 1, "pictures": [], "quotationAttachmentBOList": [], "itemGroupList": [{"id": 47112, "sourceId": 10687, "sourceType": 3, "customerLine": 1, "customerLineInt": None, "qty": 5, "selectStatus": 1, "customerProductName": "S2404883", "quotationItemList": [
            {"id": 43908, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2404883", "productName": "HEADLAMP ASSY, RH F653", "productNameTh": "HEADLAMP ASSY, RH F653", "oeNumber": "81110-BZ390", "brandSku": None, "quantity": 5, "salesPrice": 2817.74, "salesPriceWithoutVat": 2633.4, "salesAmountWithoutVat": 13167, "cataloguePrice": 3420, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None, "customerLine": 3, "skuId": 849038,
             "saleOrgId": 6, "skuOrgId": 951055, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47112, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47113, "sourceId": 10687, "sourceType": 3, "customerLine": 2, "customerLineInt": None, "qty": 6, "selectStatus": 1, "customerProductName": "S2405342", "quotationItemList": [
            {"id": 43909, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2405342", "productName": "UNIT ASSY, HEADLAMP, RH F653", "productNameTh": "UNIT ASSY, HEADLAMP, RH F653", "oeNumber": "81130-BZ260", "brandSku": None, "quantity": 6, "salesPrice": 2035.03, "salesPriceWithoutVat": 1901.9, "salesAmountWithoutVat": 11411.4, "cataloguePrice": 2470, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None, "customerLine": 4,
             "skuId": 849497, "saleOrgId": 6, "skuOrgId": 951514, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47113, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47114, "sourceId": 10687, "sourceType": 3, "customerLine": 3, "customerLineInt": None, "qty": 7, "selectStatus": 1, "customerProductName": "S2328820", "quotationItemList": [
            {"id": 43910, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2328820", "productName": "SUPPORT, FR BUMPER SIDE, RH F653", "productNameTh": "SUPPORT, FR BUMPER SIDE, RH F653", "oeNumber": "52115-BZ120", "brandSku": None, "quantity": 7, "salesPrice": 251.29, "salesPriceWithoutVat": 234.85, "salesAmountWithoutVat": 1643.95, "cataloguePrice": 305, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None, "customerLine": 5,
             "skuId": 772975, "saleOrgId": 6, "skuOrgId": 874991, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47114, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47115, "sourceId": 10687, "sourceType": 3, "customerLine": 4, "customerLineInt": None, "qty": 8, "selectStatus": 1, "customerProductName": "S2336491", "quotationItemList": [
            {"id": 43911, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2336491", "productName": "LOCK ASSY, HOOD F653", "productNameTh": "LOCK ASSY, HOOD F653", "oeNumber": "53510-BZ250", "brandSku": None, "quantity": 8, "salesPrice": 885.69, "salesPriceWithoutVat": 827.75, "salesAmountWithoutVat": 6622, "cataloguePrice": 1075, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None, "customerLine": 6, "skuId": 780646, "saleOrgId": 6,
             "skuOrgId": 882662, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47115, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47116, "sourceId": 10687, "sourceType": 3, "customerLine": 5, "customerLineInt": None, "qty": 9, "selectStatus": 1, "customerProductName": "S2333947", "quotationItemList": [
            {"id": 43912, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2333947", "productName": "MOULDING, RADIATOR GRILLE, UPR F653", "productNameTh": "MOULDING, RADIATOR GRILLE, UPR F653", "oeNumber": "53121-BZ220", "brandSku": None, "quantity": 9, "salesPrice": 4675.63, "salesPriceWithoutVat": 4369.75, "salesAmountWithoutVat": 39327.75, "cataloguePrice": 5675, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None,
             "customerLine": 7, "skuId": 778102, "saleOrgId": 6, "skuOrgId": 880118, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47116, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47117, "sourceId": 10687, "sourceType": 3, "customerLine": 6, "customerLineInt": None, "qty": 7, "selectStatus": 1, "customerProductName": "S2328077", "quotationItemList": [
            {"id": 43913, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2328077", "productName": "REINFORCEMENT SUB-ASSY, FR BUMPER F653", "productNameTh": "REINFORCEMENT SUB-ASSY, FR BUMPER F653", "oeNumber": "52021-BZ220", "brandSku": None, "quantity": 7, "salesPrice": 1112.27, "salesPriceWithoutVat": 1039.5, "salesAmountWithoutVat": 7276.5, "cataloguePrice": 1350, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None,
             "customerLine": 8, "skuId": 772232, "saleOrgId": 6, "skuOrgId": 874248, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47117, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47118, "sourceId": 10687, "sourceType": 3, "customerLine": 7, "customerLineInt": None, "qty": 5, "selectStatus": 1, "customerProductName": "S2333618", "quotationItemList": [
            {"id": 43914, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2333618", "productName": "GRILLE, RADIATOR F653", "productNameTh": "GRILLE, RADIATOR F653", "oeNumber": "53111-BZ370", "brandSku": None, "quantity": 5, "salesPrice": 1899.09, "salesPriceWithoutVat": 1774.85, "salesAmountWithoutVat": 8874.25, "cataloguePrice": 2305, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None, "customerLine": 9, "skuId": 777773,
             "saleOrgId": 6, "skuOrgId": 879789, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47118, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47119, "sourceId": 10687, "sourceType": 3, "customerLine": 8, "customerLineInt": None, "qty": 6, "selectStatus": 1, "customerProductName": "S2332755", "quotationItemList": [
            {"id": 43915, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2332755", "productName": "SUPPORT SUB-ASSY, RADIATOR, LWR F653", "productNameTh": "SUPPORT SUB-ASSY, RADIATOR, LWR F653", "oeNumber": "53028-BZ140", "brandSku": None, "quantity": 6, "salesPrice": 679.72, "salesPriceWithoutVat": 635.25, "salesAmountWithoutVat": 3811.5, "cataloguePrice": 825, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None,
             "customerLine": 10, "skuId": 776910, "saleOrgId": 6, "skuOrgId": 878926, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47119, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}, {"id": 47120, "sourceId": 10687, "sourceType": 3, "customerLine": 9, "customerLineInt": None, "qty": 8, "selectStatus": 1, "customerProductName": "S2298228", "quotationItemList": [
            {"id": 43916, "quotationId": 10687, "shopId": 2, "shopName": "EGG Search", "supplierId": None, "eggSku": "S2298228", "productName": "RADIATOR ASSY F653", "productNameTh": "RADIATOR ASSY F653", "oeNumber": "16400-BZ690", "brandSku": None, "quantity": 8, "salesPrice": 16918.79, "salesPriceWithoutVat": 15811.95, "salesAmountWithoutVat": 126495.6, "cataloguePrice": 20535, "discount": 23, "editSalesPriceReason": None, "sellOrderItemId": None, "customerLine": 11, "skuId": 742383,
             "saleOrgId": 6, "skuOrgId": 844399, "supplierPickUpTime": None, "plannedDeliveryTime": None, "groupId": 47120, "selectStatus": 1, "canEditDiscount": True, "thirdPartyShopSku": False}]}], "customerInquiryTimeLong": 1584688000000, "firstReactionTimeLong": 1584688000000, "answerToCustomerTimeLong": 1584688000000, "customerConfirmQuotationTimeLong": 1586347300000, "carPlateNo": "", "vinCode": "", "customerReferenceOrderNo": ""}

    if customer_type == "Normal":
        quotation_result = session.post(
            url=host + '/beetle/qms/web/quotation/create',
            headers=headers,
            data=json.dumps(quotation_data_normal_search)
        )
    elif customer_type == "Insurance":
        quotation_result = session.post(
            url=(host + '/beetle/qms/web/quotation/create'),
            headers=headers,
            data=json.dumps(quotation_data_insurance_search)
        )
    quotation_result_final = json.loads(quotation_result.content)
    if quotation_result.status_code != 200 and 200 != quotation_result_final['code']:
        logger.error("Can not create quotation, please check service!")
        return None
    elif 200 != quotation_result_final['code']:
        logger.error("Can not create quotation !")
        return None
    else:
        quotation_id = quotation_result_final["data"]["id"]

    logger.info("Quotation ID is : " + str(quotation_id))

    sql = "select customerId,quotationNo from erp.cms_egg_search_quotation where id =" + str(quotation_id)
    if host == "http://erp.test.jimuitech.com":
        conn = mysql_conn.get_cur(environment="test")["conn"]
        cur = mysql_conn.get_cur(environment="test")["cur"]
    elif host == "http://erp.uat.jimuitech.com":
        conn = mysql_conn.get_cur(environment="UAT")["conn"]
        cur = mysql_conn.get_cur(environment="UAT")["cur"]
    elif host == "http://erp.stable.jimuitech.com":
        conn = mysql_conn.get_cur(environment="stable")["conn"]
        cur = mysql_conn.get_cur(environment="stable")["cur"]
    cur.execute(sql)
    data = cur.fetchall()
    if len(data) == 0:
        logger.error("Can not found quotation No. with ID : " + str(quotation_id))
        return None
    logger.info("Quotation No. is : " + str(data[0][1]))
    conn.commit()
    if quotation_status != "Created":
        quoted_data = {}
        quoted_result = session.post(
            url=host + "/platform/quotation/chat/sendToCustomer/" + str(quotation_id),
            headers=headers,
            data=quoted_data
        )

        if quoted_result.status_code != 200 and "200" != json.loads(quoted_result.content)['code']:
            logger.error("Can not send quotation to customer, please check service!")
            return None
        elif "200" != json.loads(quoted_result.content)['code']:
            logger.error("Can not send quotation to customer with quotation id : " + str(quotation_id))
            return None
        elif not json.loads(quoted_result.content)['data']:
            logger.error("Can not send quotation to customer with quotation id : " + str(quotation_id))
            return None
        else:
            logger.info("Send quotation to customer with quotation id : " + str(quotation_id) + " success !")

    if quotation_status == "OrderConverted":
        convert_to_order_result = session.get(url=host + "/platform/oms/quotation/convertToOrder/" + str(quotation_id),
                                              headers=headers
                                              )
        convert_to_order_final = json.loads(convert_to_order_result.content)
        if convert_to_order_result.status_code == 200 and convert_to_order_final["code"] == "200":
            quotation_number = convert_to_order_final["data"]
            logger.info("Converted quotation to Order with quotation ID : " + str(quotation_id) + " success !")
        else:
            logger.error("Can not Converted to Order with quotation ID : " + str(quotation_id))

        search_data = {
            "page": 1,
            "limit": 10,
            "quotationNo": quotation_number,
            "orderDateEnd": "",
            "orderDateStart": "",
            "plannedDeliveryStartTime": "",
            "plannedDeliveryEndTime": "",
            "supplierPickUpStartTime": "",
            "supplierPickUpEndTime": ""
        }

        order_list_result = session.post(url=host + "/platform/client/eggSearch/order/searchList",
                                         headers=headers,
                                         data=json.dumps(search_data))
        order_list_final = json.loads(order_list_result.content)

        if order_list_result.status_code == 200 and order_list_final["code"] == "200":
            for order in order_list_final["data"]["items"]:
                print(order["quotationNo"])
                orders.append(order["quotationNo"])
        else:
            logger.error()
    else:
        quotation_number_result = session.get(
            url=host + "/beetle/qms/web/quotation/detail/" + str(quotation_id),
            headers=headers,
            data={}
        )
        if quotation_number_result.status_code == 200 and json.loads(quotation_number_result.content)["code"]:
            quotation_number = json.loads(quotation_number_result.content)["data"]["quotationNo"]
            orders.append(quotation_number)
            logger.info("Quotation create success, number is : " + quotation_number)
    return orders


def create_order(host, customer_type, payment_method, order_type, order_status, token_needed):

    global quotation_number, cur, conn, quotation_result, eggPaymentMethodCode
    orders = []
    session = requests.session()
    headers = {
        "token": token_needed,
        "countryId": "1001",
        "Content-Type": "application/json"
    }
    if payment_method == "CreditPayment":
        eggPaymentMethodCode = 1
    elif payment_method == "eggPaymentMethodCode":
        eggPaymentMethodCode = 7
    elif payment_method == "BankTransferBeforeDelivery":
        eggPaymentMethodCode = 6

    if order_type == "EGG Buy":
        egg_buy_data = {
            "createTime": 1586832300000,
            "warehouseId": "",
            "clientUserId": 17965,
            "orderType": "EGG_BUY",
            "shippingFee": 66,
            "sellOrderItems":
                [
                    {
                        "skuOrgId": 10,
                        "standardPrice": "183.00",
                        "salesPriceWithoutVat": "171.0280373832",
                        "goodsName": "BOSCH Oil filter 1457437001 1 pcs BENZ W202 /W203 C200, C220 /W204 C200/ W210 / W211 E200, E220, E-CLASS S211 200 220 270 CDI",
                        "availableStock": 1040,
                        "quantity": "4",
                        "eggSku": "Y39105039339",
                        "activityId": None,
                        "activityGoodsSkuId": None,
                        "discountJson": None,
                        "activityDiscount": 0,
                        "isComplimentary": False
                    },
                    {
                        "skuOrgId": 148,
                        "standardPrice": "191.00","salesPriceWithoutVat":"178.5046728972","goodsName":"BOSCH SN 10W40 Mega X6 Semi - Synthetic Lubricant 1987L24064   1L 1 bottle","availableStock":1000,"quantity":"2","eggSku":"Y39101010363","activityId": None,"activityGoodsSkuId": None,"discountJson": None,"activityDiscount":0,"isComplimentary": False}],"remark":"","platform":"","priceIdentityId":1,"shipId":"SH26184_1","mobile":"970163272","contact":"Yang Yunheng","province":"Bangkok","stateId":1001,"city":"Ratchathewi","cityId":1038,"district":"Bang Bon","districtId":1001,"address":"Khwaeng Makkassan, Khet Ratchathewi, Krung Thep Maha Nakhon 10400","expectedDelivery":3,"activityDisAmount":0,"orderAmount":"1180.00","shippingCouponAmount":0,"couponDiscount": 0, "myCouponIdList": [], "eggPaymentMethodInteger": eggPaymentMethodCode}
        egg_buy_result = session.post(
            url=host + "/platform/oms/order/createOrder",
            headers=headers,
            data=egg_buy_data
        )

    quotation_data_normal_search = {
        "salesAmount":21938.01,
        "createSource":"",
        "customerId":17965,
        "lineId":"",
        "internalRemark":"",
        "customerRemark":"",
        "expectedDelivery":3,
        "eggPaymentMethodCode":eggPaymentMethodCode,
        "allPutInStorage":0,
        "quotationShipIdInfoVO":
            {"stateId":32535,
             "province":"Trat",
             "cityId":32538,
             "city":"Khlong Yai",
             "districtId":32538,
             "district":"Khlong Yai",
             "address":"测试啦啦啦啦",
             "shipId":"SH17965_1",
             "contact":"Test ID",
             "mobile":"151515151"
             },
        "quotationVehicleTypeList":
            [
                {
                    "vehicleBrandId":2,
                    "vehicleSerialId":1397,
                    "yearCapacityId":"",
                    "vehicleModelId":""
                }
            ],
        "priceIdentityId":1,
        "pictures":[],
        "quotationAttachmentBOList":[],
        "itemGroupList":
            [
                {
                    "customerProductName":"8980985860",
                    "customerLine":1,
                    "qty":3,
                    "selectStatus":1,
                    "quotationItemList":[
                        {
                            "skuOrgId":607235,
                            "skuId":571685,
                            "orgId":6,
                            "materialId":2061066,
                            "eggSku":"8980985860",
                            "brand":"ISUZU",
                            "oeNumber":"8980985860",
                            "brandSku": None,
                            "productName":"ชุดไฟท้าย TFR/TFS'2007",
                            "productNameLocal":"ชุดไฟท้าย TFR/TFS'2007",
                            "productNameBi": None,
                            "materialType": 1,
                            "shopId":2,
                            "shopName":"EGG Search",
                            "salesPriceWithoutVat":652,
                            "salesPrice":697.64,
                            "salesAmountWithoutVat": None,
                            "cataloguePrice":815,
                            "discount":20,
                            "distanceInt":8015,
                            "distance":"8KM",
                            "latestReplacementOeList": [],
                            "eggShopPutOnSku":    False,
                            "checked":   True,
                            "productNameTh":"ชุดไฟท้าย TFR/TFS'2007",
                            "selectStatus":1
                        }
                    ]
                },
                {
                    "customerProductName":"8974050051",
                    "customerLine":2,
                    "qty":12,
                    "selectStatus":1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId":582297,
                                "skuId":546747,
                                "orgId":6,
                                "materialId":2036128,
                                "eggSku":"8974050051",
                                "brand":"ISUZU",
                                "oeNumber":"8974050051",
                                "brandSku": None,
                                "productName":"สติกเกอร์ TFR/TFS'2007",
                                "productNameLocal":"สติกเกอร์ TFR/TFS'2007",
                                "productNameBi": None,
                                "materialType":1,
                                "shopId":2,
                                "shopName":"EGG Search",
                                "salesPriceWithoutVat":36,
                                "salesPrice":38.52,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice":45,
                                "discount":20,
                                "distanceInt":8015,
                                "distance":"8KM",
                                "latestReplacementOeList":[],
                                "eggShopPutOnSku": False,
                                "checked":   True,
                                "productNameTh":"สติกเกอร์ TFR/TFS'2007",
                                "selectStatus":1
                            }
                        ]
                },
                {
                    "customerProductName":"B45A34015C",
                    "customerLine":3,
                    "qty":6,
                    "selectStatus":1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId":335289,
                                "skuId":299739,
                                "orgId":6,
                                "materialId":1789120,
                                "eggSku":"B45A34015C",
                                "brand":"Mazda",
                                "oeNumber":"B45A34015C",
                                "brandSku": None,
                                "productName":"COVER,DUST",
                                "productNameLocal":"ยางครอบกันฝุ่น",
                                "productNameBi": None,
                                "materialType":1,
                                "shopId":2,
                                "shopName":"EGG Search",
                                "salesPriceWithoutVat":463.5,
                                "salesPrice":495.95,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice":515,
                                "discount":10,
                                "distanceInt":8015,
                                "distance":"8KM",
                                "latestReplacementOeList":[],
                                "eggShopPutOnSku":    False,
                                "checked":   True,
                                "productNameTh":"ยางครอบกันฝุ่น",
                                "selectStatus":1
                            }
                        ]
                },
                {
                    "customerProductName":"D72101HZ1A",
                    "customerLine":4,
                    "qty":3,
                    "selectStatus":1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId":313060,
                                "skuId":289558,
                                "orgId":6,
                                "materialId":1766891,
                                "eggSku":"D72101HZ1A",
                                "brand":"Nissan",
                                "oeNumber":"D72101HZ1A",
                                "brandSku":"",
                                "productName":"BOOSTER ASSY-BRAKE",
                                "productNameLocal":"หม้อลมเบรค มี IDLE STOP K13T,ABS,E12T",
                                "productNameBi": None,
                                "materialType":1,
                                "shopId":2,
                                "shopName":"EGG Search",
                                "salesPriceWithoutVat":4203,
                                "salesPrice":4497.21,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice":5000,
                                "discount":16,
                                "distanceInt":8015,
                                "distance":"8KM",
                                "latestReplacementOeList":[],
                                "eggShopPutOnSku":   False,
                                "checked":  True,
                                "productNameTh":"หม้อลมเบรค มี IDLE STOP K13T,ABS,E12T",
                                "selectStatus":1
                            }
                        ]
                },
                {
                    "customerProductName":"S3055925",
                    "customerLine":5,
                    "qty":5,
                    "selectStatus":1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId":1602097,
                                "skuId":1284319,
                                "orgId":6,
                                "materialId":3055925,
                                "eggSku":"S3055925",
                                "brand":"Nissan",
                                "oeNumber":"540103BG1A",
                                "brandSku": None,
                                "productName":"SPRING FRONT",
                                "productNameLocal":"สปริงโช๊คอัพหน้า",
                                "productNameBi": None,
                                "materialType":1,
                                "shopId":2,
                                "shopName":"EGG Search",
                                "salesPriceWithoutVat":424,
                                "salesPrice":453.68,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice":530,
                                "discount":20,
                                "distanceInt":8015,
                                "distance":"8KM",
                                "latestReplacementOeList":[],
                                "eggShopPutOnSku":   False,
                                "checked":  True,
                                "productNameTh":"สปริงโช๊คอัพหน้า",
                                "selectStatus":1
                            }
                        ]
                },
                {
                    "customerProductName":"91604S5A003",
                    "customerLine":6,
                    "qty":8,
                    "selectStatus":1,
                    "quotationItemList":
                        [
                            {
                                "skuOrgId":55699,
                                "skuId":54326,
                                "orgId":6,
                                "materialId":1522362,
                                "eggSku":"91604S5A003",
                                "brand":"Honda",
                                "oeNumber":"91604S5A003",
                                "brandSku": None,
                                "productName":"GROMMET, HOOD STAY",
                                "productNameLocal":"หมุดยึดขาคล้ำกระโปรงหน้า",
                                "productNameBi": None,
                                "materialType":1,
                                "shopId":2,
                                "shopName":"EGG Search",
                                "salesPriceWithoutVat":75.6,
                                "salesPrice":80.89,
                                "salesAmountWithoutVat": None,
                                "cataloguePrice":84,
                                "discount":10,
                                "distanceInt":8015,
                                "distance":"8KM",
                                "latestReplacementOeList":[],
                                "eggShopPutOnSku":   False,
                                "checked":  True,
                                "productNameTh":"หมุดยึดขาคล้ำกระโปรงหน้า",
                                "selectStatus":1
                            }
                        ]
                }
            ],
        "customerInquiryTimeLong":1586416711301,
        "firstReactionTimeLong":1586416711301,
        "answerToCustomerTimeLong":1586416711301,
        "customerConfirmQuotationTimeLong":1586416711301,
        "carPlateNo":"",
        "vinCode":"",
        "customerReferenceOrderNo":""}

    quotation_data_insurance_search = {
        "salesAmount":233934.05,"createSource":"","customerId":505145,"lineId":"","internalRemark":"","customerRemark":"","expectedDelivery":3,"eggPaymentMethodCode":1,"allPutInStorage":1,"quotationShipIdInfoVO":{"stateId":1001,"province":"Bangkok","cityId":33370,"city":"Phatthanakan","districtId":33371,"district":"Suan Luang","address":"117|13","shipId":"SH505145_1","contact":"คุณวิโรจน์","mobile":"899223633"},"quotationVehicleTypeList":[{"vehicleBrandId":2,"vehicleSerialId":1397,"yearCapacityId":"","vehicleModelId":""}],"priceIdentityId":1,"pictures":[],"quotationAttachmentBOList":[],"itemGroupList":[{"id":47112,"sourceId":10687,"sourceType":3,"customerLine":1,"customerLineInt": None,"qty":5,"selectStatus":1,"customerProductName":"S2404883","quotationItemList":[{"id":43908,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2404883","productName":"HEADLAMP ASSY, RH F653","productNameTh":"HEADLAMP ASSY, RH F653","oeNumber":"81110-BZ390","brandSku": None,"quantity":5,"salesPrice":2817.74,"salesPriceWithoutVat":2633.4,"salesAmountWithoutVat":13167,"cataloguePrice":3420,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":3,"skuId":849038,"saleOrgId":6,"skuOrgId":951055,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47112,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47113,"sourceId":10687,"sourceType":3,"customerLine":2,"customerLineInt": None,"qty":6,"selectStatus":1,"customerProductName":"S2405342","quotationItemList":[{"id":43909,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2405342","productName":"UNIT ASSY, HEADLAMP, RH F653","productNameTh":"UNIT ASSY, HEADLAMP, RH F653","oeNumber":"81130-BZ260","brandSku": None,"quantity":6,"salesPrice":2035.03,"salesPriceWithoutVat":1901.9,"salesAmountWithoutVat":11411.4,"cataloguePrice":2470,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":4,"skuId":849497,"saleOrgId":6,"skuOrgId":951514,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47113,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47114,"sourceId":10687,"sourceType":3,"customerLine":3,"customerLineInt": None,"qty":7,"selectStatus":1,"customerProductName":"S2328820","quotationItemList":[{"id":43910,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2328820","productName":"SUPPORT, FR BUMPER SIDE, RH F653","productNameTh":"SUPPORT, FR BUMPER SIDE, RH F653","oeNumber":"52115-BZ120","brandSku": None,"quantity":7,"salesPrice":251.29,"salesPriceWithoutVat":234.85,"salesAmountWithoutVat":1643.95,"cataloguePrice":305,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":5,"skuId":772975,"saleOrgId":6,"skuOrgId":874991,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47114,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47115,"sourceId":10687,"sourceType":3,"customerLine":4,"customerLineInt": None,"qty":8,"selectStatus":1,"customerProductName":"S2336491","quotationItemList":[{"id":43911,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2336491","productName":"LOCK ASSY, HOOD F653","productNameTh":"LOCK ASSY, HOOD F653","oeNumber":"53510-BZ250","brandSku": None,"quantity":8,"salesPrice":885.69,"salesPriceWithoutVat":827.75,"salesAmountWithoutVat":6622,"cataloguePrice":1075,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":6,"skuId":780646,"saleOrgId":6,"skuOrgId":882662,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47115,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47116,"sourceId":10687,"sourceType":3,"customerLine":5,"customerLineInt": None,"qty":9,"selectStatus":1,"customerProductName":"S2333947","quotationItemList":[{"id":43912,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2333947","productName":"MOULDING, RADIATOR GRILLE, UPR F653","productNameTh":"MOULDING, RADIATOR GRILLE, UPR F653","oeNumber":"53121-BZ220","brandSku": None,"quantity":9,"salesPrice":4675.63,"salesPriceWithoutVat":4369.75,"salesAmountWithoutVat":39327.75,"cataloguePrice":5675,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":7,"skuId":778102,"saleOrgId":6,"skuOrgId":880118,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47116,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47117,"sourceId":10687,"sourceType":3,"customerLine":6,"customerLineInt": None,"qty":7,"selectStatus":1,"customerProductName":"S2328077","quotationItemList":[{"id":43913,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2328077","productName":"REINFORCEMENT SUB-ASSY, FR BUMPER F653","productNameTh":"REINFORCEMENT SUB-ASSY, FR BUMPER F653","oeNumber":"52021-BZ220","brandSku": None,"quantity":7,"salesPrice":1112.27,"salesPriceWithoutVat":1039.5,"salesAmountWithoutVat":7276.5,"cataloguePrice":1350,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":8,"skuId":772232,"saleOrgId":6,"skuOrgId":874248,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47117,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47118,"sourceId":10687,"sourceType":3,"customerLine":7,"customerLineInt": None,"qty":5,"selectStatus":1,"customerProductName":"S2333618","quotationItemList":[{"id":43914,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2333618","productName":"GRILLE, RADIATOR F653","productNameTh":"GRILLE, RADIATOR F653","oeNumber":"53111-BZ370","brandSku": None,"quantity":5,"salesPrice":1899.09,"salesPriceWithoutVat":1774.85,"salesAmountWithoutVat":8874.25,"cataloguePrice":2305,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":9,"skuId":777773,"saleOrgId":6,"skuOrgId":879789,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47118,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47119,"sourceId":10687,"sourceType":3,"customerLine":8,"customerLineInt": None,"qty":6,"selectStatus":1,"customerProductName":"S2332755","quotationItemList":[{"id":43915,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2332755","productName":"SUPPORT SUB-ASSY, RADIATOR, LWR F653","productNameTh":"SUPPORT SUB-ASSY, RADIATOR, LWR F653","oeNumber":"53028-BZ140","brandSku": None,"quantity":6,"salesPrice":679.72,"salesPriceWithoutVat":635.25,"salesAmountWithoutVat":3811.5,"cataloguePrice":825,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":10,"skuId":776910,"saleOrgId":6,"skuOrgId":878926,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47119,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]},{"id":47120,"sourceId":10687,"sourceType":3,"customerLine":9,"customerLineInt": None,"qty":8,"selectStatus":1,"customerProductName":"S2298228","quotationItemList":[{"id":43916,"quotationId":10687,"shopId":2,"shopName":"EGG Search","supplierId": None,"eggSku":"S2298228","productName":"RADIATOR ASSY F653","productNameTh":"RADIATOR ASSY F653","oeNumber":"16400-BZ690","brandSku": None,"quantity":8,"salesPrice":16918.79,"salesPriceWithoutVat":15811.95,"salesAmountWithoutVat":126495.6,"cataloguePrice":20535,"discount":23,"editSalesPriceReason": None,"sellOrderItemId": None,"customerLine":11,"skuId":742383,"saleOrgId":6,"skuOrgId":844399,"supplierPickUpTime": None,"plannedDeliveryTime": None,"groupId":47120,"selectStatus":1,"canEditDiscount": True,"thirdPartyShopSku":  False}]}],"customerInquiryTimeLong":1584688000000,"firstReactionTimeLong":1584688000000,"answerToCustomerTimeLong":1584688000000,"customerConfirmQuotationTimeLong":1586347300000,"carPlateNo":"","vinCode":"","customerReferenceOrderNo":""}

    if customer_type == "Normal":
        quotation_result = session.post(
            url=host + '/beetle/qms/web/quotation/create',
            headers=headers,
            data=json.dumps(quotation_data_normal_search)
        )
    elif customer_type == "Insurance":
        quotation_result = session.post(
            url=(host + '/beetle/qms/web/quotation/create'),
            headers=headers,
            data=json.dumps(quotation_data_insurance_search)
        )
    quotation_result_final = json.loads(quotation_result.content)
    quotation_id = quotation_result_final["data"]["id"]
    sql = "select customerId,quotationNo from erp.cms_egg_search_quotation where id =" + str(quotation_id)
    if host == "http://erp.test.jimuitech.com":
        conn = mysql_conn.get_cur(environment="test")["conn"]
        cur = mysql_conn.get_cur(environment="test")["cur"]
    elif host == "http://erp.uat.jimuitech.com":
        conn = mysql_conn.get_cur(environment="UAT")["conn"]
        cur = mysql_conn.get_cur(environment="UAT")["cur"]
    elif host == "http://erp.stable.jimuitech.com":
        conn = mysql_conn.get_cur(environment="stable")["conn"]
        cur = mysql_conn.get_cur(environment="stable")["cur"]
    cur.execute(sql)
    data = cur.fetchall()
    print("User ID:", data[0][0], "   Quotation ID:", quotation_id, "   Quotation No:", data[0][1])
    conn.commit()
    if order_status == "quoted":
        quoted_result = session.post(url=host + "/platform/quotation/chat/sendToCustomer/" + str(quotation_id),
                                     data=json.dumps({}),
                                     headers=headers
                                     )
        if quoted_result.status_code != 200 and json.dumps(quoted_result.content)["code"] != "200":
            print("###############################################################################")
            print("Can not send quotation to customer with quotation id : " + quotation_id)
            print("###############################################################################")

    convert_to_order_result = session.get(url=host + "/platform/oms/quotation/convertToOrder/" + str(quotation_id),
                                          headers=headers
                                          )
    convert_to_order_final = json.loads(convert_to_order_result.content)
    if convert_to_order_result.status_code == 200 and convert_to_order_final["code"] == "200":
        quotation_number = convert_to_order_final["data"]

    search_data = {
        "page": 1,
        "limit": 10,
        "quotationNo": quotation_number,
        "orderDateEnd": "",
        "orderDateStart": "",
        "plannedDeliveryStartTime": "",
        "plannedDeliveryEndTime": "",
        "supplierPickUpStartTime": "",
        "supplierPickUpEndTime": ""
    }

    order_list_result = session.post(url=host + "/platform/client/eggSearch/order/searchList",
                                     headers=headers,
                                     data=json.dumps(search_data))
    order_list_final = json.loads(order_list_result.content)

    if order_list_result.status_code == 200 and order_list_final["code"] == "200":
        for order in order_list_final["data"]["items"]:
            print(order["quotationNo"])
            print(order["sellOrderNo"])
            orders.append(order["sellOrderNo"])
    return orders
